package com.stock.service.impl;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.stock.constant.StockConstant;
import com.stock.dao.IStockProfitDataDao;
import com.stock.entity.StockProfitDataEntity;
import com.stock.service.IStockProfitDataService;
import com.stock.vo.AiStockDataResultVo;
import com.stock.vo.StockProfitDataResultVo;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class StockProfitDataService extends ServiceImpl<IStockProfitDataDao, StockProfitDataEntity> implements IStockProfitDataService {

    /**
     * 初始化历史数据
     * @return
     */
    @Override
    public boolean initStockProfitData() {
        this.remove(new QueryWrapper<>());
        List<StockProfitDataEntity> profitDataList = Arrays.asList(
                new StockProfitDataEntity("2024-11-28", "0.33"),
                new StockProfitDataEntity("2024-11-29", "6.72"),
                new StockProfitDataEntity("2024-12-02", "5.05"),
                new StockProfitDataEntity("2024-12-03", "2.44"),
                new StockProfitDataEntity("2024-12-04", "18.59"),
                new StockProfitDataEntity("2024-12-05", "5.30"),
                new StockProfitDataEntity("2024-12-06", "0.77"),
                new StockProfitDataEntity("2024-12-09", "-5.23"),
                new StockProfitDataEntity("2024-12-10", "3.25"),
                new StockProfitDataEntity("2024-12-11", "2.04"),
                new StockProfitDataEntity("2024-12-12", "-1.49"),
                new StockProfitDataEntity("2024-12-13", "-0.64"),
                new StockProfitDataEntity("2024-12-16", "1.27"),
                new StockProfitDataEntity("2024-12-17", "-5.53"),
                new StockProfitDataEntity("2024-12-18", "1.47"),
                new StockProfitDataEntity("2024-12-19", "-1.92"),
                new StockProfitDataEntity("2024-12-20", "4.36"),
                new StockProfitDataEntity("2024-12-23", "-6.75"),
                new StockProfitDataEntity("2024-12-24", "1.79"),
                new StockProfitDataEntity("2024-12-25", "-3.95"),
                new StockProfitDataEntity("2024-12-26", "-9.30"),
                new StockProfitDataEntity("2024-12-27", "-11.45"),
                new StockProfitDataEntity("2024-12-30", "-14.55"),
                new StockProfitDataEntity("2024-12-31", "-10.90"),
                new StockProfitDataEntity("2025-01-02", "-15.75"),
                new StockProfitDataEntity("2025-01-03", "-17.32")
        );
        return this.saveBatch(profitDataList);
    }

    /**
     * 获取股票收益数据
     * @param beginDate
     * @param endDate
     * @return
     */
    @Override
    public List<StockProfitDataResultVo> getStockProfitData(String beginDate, String endDate) {
        return baseMapper.getStockProfitData(beginDate,endDate);
    }

    /**
     * 获取总收益率
     * @param beginDate
     * @param endDate
     * @return
     */
    @Override
    public BigDecimal getTotalProfitRate(String beginDate, String endDate) {
        BigDecimal totalProfitRate = baseMapper.getTotalProfitRate(beginDate, endDate);
        return totalProfitRate != null ? totalProfitRate : BigDecimal.ZERO;
    }

    /**
     * 获取股票 ai 数据
     * @param queryStr
     * @return
     */
    @Override
    public List<AiStockDataResultVo> getAiStockData(String queryStr) {
        List<AiStockDataResultVo> resultList = new ArrayList<>();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 组装请求体
            String requestBody = String.format("{\"strategy_query\": \"%s\"}", queryStr);
            // 发起 POST 请求
            HttpResponse response = HttpUtil.createPost(StockConstant.AI_STOCK_URL)
                    .header("Content-Type", "application/json")
                    .body(requestBody)
                    .execute();
            // 检查响应状态
            if (!isValidResponse(response)) {
                return resultList; // 返回空列表而不是 null，避免空指针问题
            }
            // 解析响应
            String responseBody = response.body();
            JsonNode jsonResponse = objectMapper.readTree(responseBody);
            // 检查返回是否包含错误
            if (jsonResponse.has("error")) {
                return resultList;
            }
            // 提取结果数据
            JsonNode resultNode = jsonResponse.get("result");
            if (resultNode == null || !resultNode.isArray()) {
                return resultList;
            }
            // 将 JSON 数组解析为 List<AiStockDataResultVo>
            for (JsonNode node : resultNode) {
                AiStockDataResultVo stockData = new AiStockDataResultVo();
                stockData.setCode(node.get("code").asText());
                stockData.setName(node.get("name").asText());
                resultList.add(stockData);
            }
        } catch (Exception e) {
            e.printStackTrace(); // 输出异常信息，便于调试
        }
        return resultList;
    }

    /**
     * 检查响应是否有效
     */
    private boolean isValidResponse(HttpResponse response) {
        if (response == null || response.getStatus() != 200) {
            return false;
        }
        return true;
    }

}
